<script setup lang="ts">
import { createTextVNode, defineComponent, ref, watch } from 'vue';
import { getServiceBaseURL } from '@/utils/service';
import { useAuthStore } from '@/store/modules/auth';
import { fetchUpload } from '@/service/api';
import { UploadFileInfo, useLoadingBar, useMessage, useNotification } from 'naive-ui';
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL, otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
defineOptions({
  name: 'uploadImg'
});

interface Props {
  data: any
  isMultiple?: boolean
}
const props = defineProps<Props>();
interface Emits {
  (e: 'onchange', url: string): void;
}

const emit = defineEmits<Emits>();
const authStore = useAuthStore()
const auth: any = { id: authStore.userInfo.id }
const showModalRef = ref(false)
const previewImageUrlRef = ref('')
// 文件列表
const handlePreview = (file: UploadFileInfo) => {
  const { url } = file
  previewImageUrlRef.value = url as string
  showModalRef.value = true
}

const previewFileList = ref<UploadFileInfo[]>([
  // {
  //   id: 'react',
  //   name: '头像',
  //   status: 'finished',
  //   url: props.data
  // },
])
watch(props, () => {
  if (props.data) {
    previewFileList.value.push({
    id: 'react',
    name: '头像',
    status: 'finished',
    url: props.data
  })
  }
}, { immediate: true })

//
const handleCustomRequest = ({file}: any) => {
  const formData: any = new FormData();
  formData.append('file[]', file.file);
  // formData.append('auth', JSON.stringify({ id: authStore.userInfo.id }));
  fetchUpload(formData).then((res: any) => {
    if (res.data.msg === 'OK') {
      emit('onchange', res?.data?.data?.succMap['test1.png'] || '')
    }
  })
}

</script>

<template>
  <NUpload
  :custom-request="handleCustomRequest"
  :action="baseURL + '/api/editor/upload'"
  :headers="{ Authorization: 'Bearer ' + authStore.token }"
  :multiple="true"
  name="file[]"
  :data="{ auth }"
  list-type="image-card"
  :default-file-list="previewFileList"
  :max="props.isMultiple ? 100 : 1"
  @preview="handlePreview"
  >
  </NUpload>
  <NModal
    v-model:show="showModalRef"
    preset="card"
    style="width: 600px"
  >
    <img :src="previewImageUrlRef" style="width: 100%">
  </NModal>
</template>

<style scoped></style>
